
"use strict";


function CExtintView( ) {

	debug.log(this, ' New EXitview');
	this.objName = 'ExtinctView';
	var self = this;
	this.cstls = [];
	/// store name for unique id 
	this.name = 'ext';
	this.initialize();
		
};


CExtintView.prototype = {

		// init ... 
		initialize: function() {
			var self = this;
			debug.log(this, ' init CExtintView !! ');
			
			this.makeFrame();
			
			// make default 1st cstl frame 
			this.cstls[0] = this.makeCstl(0);
			this.installHandler();
			// $.each ( CDB.getCurUs	erCtsl() , function(i, c) {
				// self.makeCstl(c);
			// });
			// setInterval ( function() { self.timerFn(); }, 1000);
			this.showH_StateLight('init');
		}	,
		
		// init ... 
		makeFrame: function() {
			var self = this;
			
			$('#extinct_frame')
				// user frame 
				.append ( $('<div>' ,{'id': 'ext_frame_' + this.name , 'class':'ext_frame'})
						
						// state light, id, ref , bless
						.append( $('<header>')
							// state light, id, ref 
							.append( $('<div>').css({'float': 'left'}) 
								.append ( $('<span>')
									.append( $('<img>', {'id': 'state_light'}).attr('src' , './images/state_light_init.jpg')
										.css({'width': '20px', 'height': '20px' }) )
								)
								.append ( $('<span>').text( 'name')  ) 
								.append ( $('<span>').text( 'id')  ) 
								.append ( $('<span>').text('ll')  )
								.append ( $('<span>').text('nick')  )
								.append ( $('<span>').text('gem')  )
								.append ( $('<span>').text('ally')  )
								.append ( $('<span>').text('truce')  )
							)
							
							// bless
							.append( $('<div>').css({'float': 'right'}).css( {'margin-right': '20px'})
								.append (   $('<span>').append( $('<img>', {'class':'bless'}).attr('src' , '') ) )
								.append (   $('<span>').append( $('<img>', {'class':'bless'}).attr('src' , '') ) )
							)
						)	

						// body 
						.append( $('<div>', {'id': 'ext_cstls'}) )
						
						.append( $('<footer>') 
							
							.append ( $('<span>', {'class': 'ally_info'}).text('hall') )
							.append ( $('<span>', {'class': 'ally_info'}).text('tech') )
							// trade  state icon 
							.append (  $('<span>').append( $('<img>', {'class':'trade_state'})
										.css({'width': '30px', 'height': '30px'})
										.attr('src' , '') ) )
							.append ( $('<span>', {'class': 'trade_info'}).text('T: ') )
							.append ( $('<span>', {'class': 'trade_info'}).text(' --- ') )
							.append ( $('<span>', {'class': 'trade_info'}).text(' 1111 ') )
							.append ( $('<span>', {'class': 'trade_info'}).text('Tem x x') )
							.append ( $('<span>', {'class': 'trade_info'}).text('==') )
							.append ( $('<button>').text('GO!') )
							.append ( $('<button>').text('Stop.') )
							.append ( $('<span>', {'class': 'rumors'}).text('rumorinfo') )
							.append ( $('<button>').text('Config') )
						)
				
				);

		}	,
		

		makeCstl: function(idx, cstl) {
			var self = this;

			// set defualt. info cstl 
			if ( !cstl ) {
				cstl = { };
			}
			/// make cstl  UI  per each ctsl
			//var cstls = CDB.getCurUserCtsl();
			
			$('#ext_frame_' + this.name +' footer')
						//  res, 
						// lv , ing job 
						// cds ,  study, blds 						
				.before( $('<section>', {'id': 'ext_cstl' + idx})
							
							// ing job , res  
							// .append ( $('<div>', {'id': 'ext_cstl_name'}).text('c name'))
							.append ( $('<div>', {'id': 'ext_cstl_row1'})
								.append( $('<ul>')//.attr({'display' : 'inline'})
									.append ( $('<li>').css( {'width': '10%'}).append( $('<span>').text ( 'n:cname') )  )
									.append ( $('<li>').css( {'width': '20%'}).append( $('<span>').text ( 'ing..') )  )
									.append ( $('<li>').css( {'width': '28%'}).append( $('<span>').text ( 'ress') )  )
									.append ( $('<li>').css( {'width': '28%'}).append( $('<span>').text ( 'sols') )  )
								)
							)
							
										// seperator 
							.append ( $('<div>')	.css({'clear':'both'})) 
							
							
							// sttudy, blds 
							.append ( $('<div>', {'id': 'ext_details'}) //.css( {'float': 'left'} )
								// blds
								.append ( $('<div>', {'id': 'ext_blds', 'class': 'ext_detail_div'}).css({'width':'45%'}).text('blds'))
									// tbls 
								// study 
								.append ( $('<div>', {'id': 'ext_study', 'class': 'ext_detail_div'}).css({'width':'45%'}).text('sty'))
								)

							// seperator 
							.append ( $('<div>')	.css({'clear':'both'})) 
								
								// cds, att , loot
								.append ( $('<div>', {'id': 'ext_details_2nd'})								
									.append ( $('<div>', {'id': 'ext_cds'}).addClass('ext_detail_div' ).css({'width':'180px'})
										.append ( $('<span>').text ( 'cds') )
										.append ( $('<p>').text ( 'cd: 1st ') )
										.append ( $('<p>').text ( 'cd: 2st ') )
									)
									// att 
									.append ( $('<div>', {'id': 'ext_att'}).addClass('ext_detail_div')
										// tlbs
									)
									// att 
									.append ( $('<div>', {'id': 'ext_hdrin' ,'class': 'ext_detail_div'}).text('hdrin').css({'width':'200px'}) )
									.append ( $('<div>', {'id': 'ext_loot'}).css({'width':'100px'}).addClass('ext_detail_div')
										.append($('<button>').text('loot')) )
								)	// 2nsd
						); // before 	
				return 'ext_cstl' + idx;
		}	,

		
	installHandler: function() {
		
			// install handler 
			// go 
			$('#ext_frame_' + this.name +  ' footer button:eq(0)').click( function () {
				debug.log(self, ' ############################# Start Cur actions ', self.name); 
				// // em.spproxy.start_sp30 ( this.name );
				// em.spactmgr.resumeUserAction (self.name);
				// self.showH_StateLight('conn');
			});

			$('#ext_frame_' + this.name +  ' footer button:eq(1)').click( function () {
				// stop
				debug.log(self, ' ############################# Stop Cur actions ' , self.name); 
				// // em.spproxy.stop_sp30 ( self.name );
				// em.spactmgr.stopUserAction (self.name);
				// self.showH_StateLight('stop');
				
			});
			
	},
	/*
		update !!!!
	*/
	
	UPDATE___: function() {},
	
	 					/*
							"user":{"id":18949,"nick":"greateload","nationid":1,"level":42,"money":345,"guild":"greate","guildid":262,
					"gpower":1,"gflag":97,"protection":0,"p_end":1322486844,"status":0,
					"city":[
						{"id":22289,"name":"centercast","landtype":3,"x":61,"y":19},
						{"id":22336,"name":"heaven","landtype":4,"x":61,"y":18},
						{"id":22349,"name":"Spacecastl","landtype":2,"x":60,"y":17},
						{"id":22423,"name":"Forward","landtype":5,"x":62,"y":17}],
					"conq":[0,0,null,5],
					"gift":[{"id":168,"msg":"","s":0}],"pvp":0
					},
					*/
					/*
														.append ( $('<span>').text( 'name')  ) 
								.append ( $('<span>').text( 'id')  ) 
								.append ( $('<span>').text('ll')  )
								.append ( $('<span>').text('nick')  )
								.append ( $('<span>').text('gem')  )
								.append ( $('<span>').text('ally')  )
								.append ( $('<span>').text('truce')  )
					*/
	update_userinfo_user: function(user) {
		$('#ext_frame_' + this.name +  ' header div span').eq(1).text(user.id);
		$('#ext_frame_' + this.name +  ' header div span').eq(2).text(this.name);
		$('#ext_frame_' + this.name +  ' header div span').eq(3).text(user.nick);
		$('#ext_frame_' + this.name +  ' header div span').eq(4).text(user.money);
		$('#ext_frame_' + this.name +  ' header div span').eq(5).text(user.guild);
		$('#ext_frame_' + this.name +  ' header div span').eq(6).text(user.protection);
	},
	
	update_userinfo_city: function(cities) {
		var self = this;
		$.each( cities, function(i, c) {
			if ( ! self.cstls[i]  ) {
				self.makeCstl(i, c);
			}
			// update info 
			$('#ext_frame_' + this.name +' section #ext_cstl' + i + ' ext_cstl_row1 ul li').eq(0).find('span').text( '' + i + ':' + c.name);
					// $('#ext_frame_' + this.name +  ' section #ext_ing_res ul li').eq(1).find('span').text(res_s );
							// .append ( $('<div>', {'id': 'ext_cstl_row1'})
								// .append( $('<ul>')//.attr({'display' : 'inline'})
									// .append ( $('<li>').css( {'width': '10%'}).append( $('<span>').text ( 'n:cname') )  )
			});
	},
	
	
	updateContents: function(username) {

		// get user info : 
		// same svr, 
		
		
		// update id, ref   
		
		// update cit info 
		//bless  , res, lv  
		
		 
		var cstlinfo = em.cstlmgr.getCurCstl();
		var cstlidx =  em.cstlmgr.getCurCstlIdx();
		console.log (cstlinfo);
				
	},		
	

	showHeader: function(info) {
		// state light
		$('#ext_frame_' + this.name +  ' header div span').eq(1).text(info.lv);
		$('#ext_frame_' + this.name +  ' header div span').eq(2).text(info.username);
		$('#ext_frame_' + this.name +  ' header div span').eq(3).text(info.ref);
	}, 
		
	showH_StateLight: function(state) {
		// state light
		var state_img ='';
		switch( state) {
			case 'init' :
			case 'stop' :
				state_img = './images/not_connected.jpg';
				break;
			case 'conn' :
				state_img = './images/ext_conn.jpg';
				break;
			case 'step1' :
				state_img = './images/step1.jpg';
				break;
			case 'step3' :
				state_img = './images/step3_begin.gif';
				break;
			case 'step3_begin' :
				state_img = './images/step3_begin.gif';
				break;
			case 'step3_running' :
				state_img = './images/step1_running.jpg';
				break;
		}  
		$('#ext_frame_' + this.name +  ' #state_light').attr( 'src', state_img);
	}, 

	// detail
	// res , ing  
	showRes: function(res) {
		var res_s = 'F:' + CUtil.commify(res.f) + '   W:' + CUtil.commify(res.w) 
				 + '   I:'	+ CUtil.commify(res.i);
				 
		$('#ext_frame_' + this.name +  ' section #ext_ing_res ul li').eq(1).find('span').text(res_s );
		$('#ext_frame_' + this.name +  ' section #ext_ing_res ul li').eq(2).find('span').text( '   G:' + CUtil.commify(res.g) );
	}, 
	
	// cds 
	showCDs: function(cds) {
		var con  = $('#ext_frame_' + this.name +  ' section #ext_cds');
		
			var type_styles = [ 
				{'color': 'black'},		// default
				{'color': 'black'},		// bld : 1 
				{'color': 'blue'},		// sty : 2 
				{'color': 'red'},		// train : 3 
				{'color': 'black'},		// att : 4 
			];
			  
			con.empty();
			$.each ( cds, function(_,cd) {
				var jobname = CDB.CDS.getTypeName( cd.cdtype);
				var target =  CDB.CDS.getTargetName( cd.cdtype, cd.target);
				var str = jobname + "::"+ target + ' : ';
				if ( cd.done) {
					if ( cd.cdtype == CDB.CDS.ATT) 
						return; 	// skip .. expired att 
						
					str += ' Done!';
				} else {
					// str += Math.floor(cd.secs/3600) + ':' +  Math.floor(cd.secs/60) % 60  + ':' + cd.secs % 60;
					str += CUtil.SecToString(cd.secs);
					
					if ( cd.secs < 0 ) str += ' Done' ;
				}
				
				con.append( $('<p>').css(type_styles [cd.cdtype ]).text( str) );
			});
		
	}, 
	
	// study
	showStudies: function(idx, studies) {
		var con  = $('#ext_frame_' + this.name +  ' section #ext_study');
			// studys
			con.empty();
			// add tables for each blds 
			$.each( CDB.STUDY , function (i, s) {
					if ( ! studies[s.pos]  )  return false;	// exit each loop 
					
					con.append( 
						$('<tr>', {'id': 'studies_type_row' + i })
							.append(
								$('<td>').text( s.name))
							.append(
								$('<td>').text( studies[ s.pos ][1]))	//lv
							.append(
								$('<td>').text( studies[ s.pos ][2]))	//possible 
							// .append(
								// $('<td>').text( ''))	// status 
								
								// add hidden 
							// .append($('<input>').attr('type','hidden').val(s.type)) 
							
							// .append(
								// $('<td>').width('50px').append($('<span>').attr('width','50px')
									// .append( $('<p>').text('DO') )) )	// 2 td
							)	// tr
			} );
		
	}, 
	
	// blds
	showBlds: function(city) {
		var con  = $('#ext_frame_' + this.name +  ' section #ext_blds');
			//
		// var cstl = em.cstlmgr.getCurCstl();
		
		con.empty();
		
		// add tables for each blds 
		$.each( CDB.BUILD , function (i, bld) {
				con.append( 
					$('<tr>', {'id': 'blds_type_row' + i })
						.append(
							$('<td>').text( bld.name))
						.append(
							$('<td>').text( city[ bld.pos ]))
							
							// add hidden 
							// <INPUT TYPE="hidden" NAME="objectName" VALUE="hiddenValue">
						// .append(
							// $('<td>').append($('<input>').attr('type','hidden').val(bld.type)) )
						// .append(
							// $('<td>').width('50px').append($('<button>').attr('width','30px').text('Up') ))	// 2 td
						)	// tr
 
		} );
	}, 
	
	
	
	
	
	
	updateUser : function(states) {
		// header :  lv, name, ref 
		this.showHeader({name: states.name, lv: states.grade, ref: 'n'});
		

		
	},

	startRefresh : function(states) {
		var self = this;
		this.refresh_timer = setInterval( function () {
			var states = em.spproxy.getCurUserStates();
			self.updateUser( states );
		}) ;
	},
	
	current: function() {
		$('.ext_frame').removeClass('ext_frame_current');
		$('#ext_frame_' + this.name ).addClass('ext_frame_current');
	},
	/*
	 * 	INFO VIEW 
	 *=====================================================================
		 cstl mgr interface !!         async view update  after ajax action
	*/
	__INFO_VIEW_IF: function() {},
	
	connected: function(on) {
		if ( on) {
			this.showH_StateLight('conn');
		} else {
			this.showH_StateLight('init');
		}
	},

	// lv > 30  :  
	setFinishedState: function( ) {
		this.showH_StateLight('stop');
		$('#ext_frame_' + this.name ).addClass('ext_frame_finished');
	},
	
	// login & grade.. 
	updateUserinfo: function(type, info) {
		// grade 
		if ( type == 'grade') {
			$('#ext_frame_' + this.name +  ' header div span').eq(1).text(info.grade);
		}
 		else {
			$('#ext_frame_' + this.name +  ' header div span').eq(1).text(info.level);
			$('#ext_frame_' + this.name +  ' header div span').eq(4).text(info.nick);
 		}		
	},
	
	// user DB info .. 
	setUserInfo: function(userinfo) {
		$('#ext_frame_' + this.name +  ' header div span').eq(2).text(userinfo.name);
		$('#ext_frame_' + this.name +  ' header div span').eq(3).text(userinfo.ref);
	},
	
	setAutoHntStart: function() {
	},
	updateEnhance: function() {
	},

	showBless: function(city) {
		var self = this;
		// new 
		if ( this.blessCnt != city[23].length) {
			this.bless = city[23].length;
			
			$.each (  city[23] , function(i, tem) {
				if ( tem.itemid == 166 || tem.itemid == 167 ) {
					// $('#left_header').after('#clock')d
					// console.log($('#ext_frame_ header .bless') );
					// console.log($('#ext_frame_ header img ') );
					// console.log($('#ext_frame_ header div img ') );
					// console.log($('#ext_frame_ header div span img ') );
					// console.log($('#ext_frame_ header .bless') );
					// console.log($('#ext_frame_ .bless') );
					// console.log($('.bless') );
					$('#ext_frame_' + self.name +  ' header .bless').eq(i).attr( 'src', './images/state_light_init.jpg');
				}
				
			} );
		}
	},
	
	// trade status bar 
	// status : icon type ,  result : wattime.   id: 
	showTradeStatus: function(tradeinfo) {
		// state icon
		var srcimg;
		switch (  tradeinfo.status  ) {
			case 'Enough':
						srcimg = './images/trade_enough.png';
			break;
			case 'Wait Trade':
						srcimg = './images/trade_wait.jpg';
			break;
			case 'TradingUP':
						srcimg = './images/trade_up.png';
			break;
		}
		
		$('#ext_frame_' + this.name +  ' footer  .trade_state')
								.attr( 'src', srcimg );
								
								
		// clear prev info 
		$('#ext_frame_' + this.name +  ' footer  .trade_info').text( '' );
		$('#ext_frame_' + this.name +  ' footer  .trade_info')	.eq(1).text( tradeinfo.status  ) 
		
		//status str
		//  trainding .. show price  
		if ( tradeinfo.price ) {
			$('#ext_frame_' + this.name +  ' footer  .trade_info')
							   // ( $('<span>').text('T: ') )
							.eq(3).text( tradeinfo.id + ' ::  ' +   tradeinfo.price ); 		// .append ( $('<span>').text('UP') )
		}
		
		if ( tradeinfo.remainsec) {
						$('#ext_frame_' + this.name +  ' footer  .trade_info')
							.eq(2).text(  CUtil.SecToString( tradeinfo.remainsec)  
										+ '  ,' +  CUtil.TimeToString( new Date( $.now() + tradeinfo.remainsec * 1000) )   
								)			;
		} 
		
		if ( tradeinfo.temcnt) {
						$('#ext_frame_' + this.name +  ' footer  .trade_info')
							.eq(4).text(  ' X '  + tradeinfo.temcnt)  ;
		}
		
	},


	informAllyState: function(info, cool) {
		// state icon
/*
		var srcimg;
		switch (  tradeinfo.status  ) {
			case 'Enough':
						srcimg = './images/trade_enough.png';
			break;
			case 'Wait Trade':
						srcimg = './images/trade_wait.jpg';
			break;
			case 'TradingUP':
						srcimg = './images/trade_up.png';
			break;
		}
		
		$('#ext_frame_' + this.name +  ' footer  .trade_state')
								.attr( 'src', srcimg );
								*/

								
		// clear prev info 
		$('#ext_frame_' + this.name +  ' footer  .ally_info').text( '' );
		var str = info +  ( ( cool ) ? ' Cool:' + cool :  '' );
		$('#ext_frame_' + this.name +  ' footer  .ally_info').text( str ) ;
		
	},


	/*
	 *   CSTL  VIEW 
	 *=====================================================================
		 cstl mgr interface !!         async view update  after ajax action
	*/
	__CSTL_VIEW_IF: function() {},
	
			// att info  
	pushAttInfo: function(index, attinfo) {
		// nothing to do 
		},
	
	// after get userinfo  update city  : name, xy  
	setCityInfo: function(index, city) {
		// nothing to do 
			
		},
		
			// focus cur cstl
	setCurCstl: function(index) {
	// nothing to do 
	},
	
	// res &  name : 
	setCstlState: function(index, cstlinfo) {
		this.showRes( cstlinfo.res );
		
			// this.showRes( states.cstl.res) ;
		// this.showCds( states.cstl.cds) ;
		this.showBlds( cstlinfo.city) ;
		// nothing : with cstl name 	
	},
	
	updateCDs: function(index, cds){
		this.showCDs( cds);
	},
	
		// clear index castl : before start 
	clearCstlDetail: function(index) {
		
	},
	// show cur task ing 
	showCurIng: function(step, task , result) {
		if ( this.step !=  step ) {
			this.showH_StateLight('step' + step);
			this.step = step;
		}
		
		var task_str ;
		if (typeof task === 'string') {
				task_str = task;
		} else {
			task_str = task.name;
		}
		if ( result ) {
			var res =  (result.succ) ? 'SUCC!' : 'Fail' ; 
			task_str +=  ' ' + res;
		}
		$('#ext_frame_' + this.name +  ' section #ext_ing_res ul li').eq(0).find('span').text(task_str  );
	},
	
};


function CLootView(  ) {

	this.objName = 'CLootView';
	this.initialize();
};


CLootView.prototype = {
	// create each view..  
	initialize: function() {

	},
};


function CViewProxy(  ) {

	this.objName = 'CViewProxy';
	this.initialize();
};


CViewProxy.prototype = {
	// create each view..  
	initialize: function() {
		this.extview = new CExtintView();
		this.lootview = new CLootView();
		
	},
	
	update_userinfo_user: function(user) {
		this.extview.update_userinfo_user(user);
	},
	
	update_userinfo_city: function(cities) {
		this.extview.update_userinfo_city(cities);
	},
	
};